const { Asset, Setting } = require("../db/index.cjs");
const { Op } = require("sequelize");
const dayjs = require("dayjs");

const data = [
	{
		channel: 'asset.getPagedList',
		listener: async (evt, params, { pageNum, pageSize }, onlyWarning = false) => {
			const data = await Setting.findOne({
				where: {
					key: 'advanceNoticeDays'
				}
			})
			const value = data ? data.dataValues.value : 7
			return onlyWarning ? Asset.findAndCountAll({
				where: {
					...params,
					nextTraceabilityDate: {
						[Op.lt]: dayjs().add(-Number(value), 'day')
					}
				}
			}) : Asset.findAndCountAll({
				where: params,
				limit: pageSize,
				offset: (pageNum - 1) * pageSize,
			})
		}
	},
	{
		channel: 'asset.getById',
		listener: (evt, id) => {
			return Asset.findOne({
				where: {
					id: {
						[Op.eq]: id
					}
				}
			})
		}
	},
	{
		channel: 'asset.save',
		listener: (evt, data) => {
			return Asset.findOne({ where: { id: data.id } }).then(data1 => {
				console.log('save', data1)
				if (data1) {
					return Asset.update(data, { where: { id: data.id } })
				} else {
					return Asset.create(data)
				}
			})
		}
	},
	{
		channel: 'asset.deleteById',
		listener: (evt, id) => {
			return Asset.destroy({ where: { id } })
		}
	},
	{
		channel: 'asset.saveBatch',
		listener: (evt, data) => {
			if (!Array.isArray(data)) {
				data = [data]
			}
			return Asset.bulkCreate(data, {
				updateOnDuplicate: [
					'name',
					'spec',
					'accuracy',
					'manufacturer',
					'factoryNumber',
					'traceabilityMethod',
					'calibrationParameters',
					'traceabilityDate',
					'nextTraceabilityDate',
					'traceabilityConclusion',
					'traceabilityInstitution',
					'certificateNumber',
					'remark'
				]
			})
		}
	}
]

module.exports = data
